package cn.basic.auth.service.impl;

import cn.basic.auth.dto.LoginDTO;
import cn.basic.auth.service.ILoginService;
import cn.basic.org.domain.Employee;
import cn.basic.org.domain.EmployeeInfo;
import cn.basic.org.mapper.EmployeeMapper;
import cn.basic.org.vo.result.EmployeeInfoVo;
import cn.basic.utils.BasicMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * description: ILoginServiceImpl <br>
 * date: 2023/3/7 11:30 <br>
 * author: ZhaoLc <br>
 * version: 1.0 <br>
 */
@Service
public class ILoginServiceImpl implements ILoginService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 校验非空信息
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码不能为空！请检查后重新提交！");
        }
        // 判断员工信息是否存在 不存在直接返回错误
        Employee employee = employeeMapper.loadByUserName(username);
        //EmployeeInfoVo employeeInfoVo = employeeMapper.loadInfoById(employee.getId());

        // 员工存在 判断密码是否一致
        if (Objects.isNull(employee)) {
            throw new RuntimeException("用户名或密码错误！");
        }

        // 密码不一致，说明密码错误
        if (!password.equals(employee.getPassword())){
            throw new RuntimeException("用户名或密码错误！");
        }

        // 生成随机字符串作为Map的Key
        String token = UUID.randomUUID().toString();

        // 将token和employee存入map
        BasicMap.loginMap.put(token,employee);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        employee.setPassword("");
        resultMap.put("loginUser",employee);
        // resultMap.put("loginUserInfo",employeeInfoVo);
        // 定义返回的Map对象
        return resultMap;
    }
}
